import router from './index'
import { useUserStore, useSystemStore } from '@/stores'

// 需要登录才能访问的页面
const permissionPage = [
  '/vehicle/add',
  '/member/user',
  '/member/order',
  '/member/publish'
]
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const systemStore = useSystemStore()
  // 如果没有数据字典则查询
  if (Object.keys(systemStore.dictionary).length <= 0) {
    systemStore.setDictionary()
  }

  //1. 用户有token
  if (userStore.token) {
    // 1. 访问登录页则跳转到首页
    if (to.path === '/login') {
      next('/')
    } else {
      // 2. 用户信息不存在则发请求获取
      if (!userStore.userInfo.id) {
        // 发送请求获取用户信息存入pinia
        userStore.setUserInfo()
      }
      // 放行
      next()
    }
  } else {
    // 访问权限页则跳转到登录页
    if (permissionPage.includes(to.path)) {
      // 跳转到登录页
      // eslint-disable-next-line no-undef
      ElMessage({ type: 'error', message: '请先登录' })
      next(`/login?redirect=${to.path}`)
    } else {
      next()
    }
  }
})
